package com.lagou.sqlSession;

import com.lagou.pojo.Configuration;
import com.lagou.pojo.MappedStatement;

import java.lang.reflect.*;
import java.util.List;
import java.util.Map;

public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;

    public DefaultSqlSession(Configuration configuration) {
        this.configuration = configuration;
    }

    @Override
    public <E> List<E> selectList(String statementId, Object... params) throws Exception {

        //将要完成对simpleExecutor的query方法调用
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        List<Object> queryList = simpleExecutor.query(configuration, configuration.getMappedStatementMap().get(statementId), params);

        return (List<E>) queryList;
    }

    @Override
    public <T> T selectOne(String statementId, Object... params) throws Exception {
        List<Object> objectList = selectList(statementId, params);
        if (objectList.size() == 1) {
            return (T) objectList.get(0);
        } else {
            throw new RuntimeException("返回结果为空或返回结果过多");
        }
    }

    @Override
    public int insert(String statementId, Object... params) throws Exception {
        return update(statementId, params);
    }

    @Override
    public int update(String statementId, Object... params) throws Exception {
        SimpleExecutor simpleExecutor = new SimpleExecutor();
        MappedStatement mappedStatement = configuration.getMappedStatementMap().get(statementId);
        return simpleExecutor.update(configuration, mappedStatement, params);
    }

    @Override
    public int delete(String statementId, Object... params) throws Exception {
        return update(statementId, params);
    }

    @Override
    public <T> T getMapper(Class<?> mapperClass) {
        //使用JDK动态代理为Dao接口生成代理对象，并返回
        Object proxyInstance = Proxy.newProxyInstance(DefaultSqlSession.class.getClassLoader(), new Class[]{mapperClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //底层都还是去执行JDBC代码   //根据不同SQL语句，来调用select|insert|update|delete方法
                //准备参数 1：statementId:sql语句唯一标识：namespace.id=接口全限定名.方法名
                //方法名：findAll
                String methodName = method.getName();
                String className = method.getDeclaringClass().getName();
                String statementId = className + "." + methodName;

                Map<String, MappedStatement> mappedStatementMap = configuration.getMappedStatementMap();
                MappedStatement mappedStatement = mappedStatementMap.get(statementId);
                String sql = mappedStatement.getSql();
                String sqlCommand = sql.substring(0, 6);
                switch (sqlCommand) {
                    case "select":
                        //准备参数 2：params:args
                        //获取被调用方法的返回值类型
                        Type genericReturnType = method.getGenericReturnType();
                        //判断是否进行了 泛型类型参数化
                        if (genericReturnType instanceof ParameterizedType) {
                            List<Object> objects = selectList(statementId, args);
                            return objects;
                        } else {
                            return selectOne(statementId, args);
                        }
                    case "insert":
                        return insert(statementId, args);
                    case "update":
                        return update(statementId, args);
                    case "delete":
                        return delete(statementId, args);
                }

                return null;
            }
        });

        return (T) proxyInstance;
    }
}
